package com.igorkundovic.guitarstab.service_hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.igorkundovic.guitarstab.Comment;
import com.igorkundovic.guitarstab.User;
import com.igorkundovic.guitarstab.beans.CommentBean;
import com.igorkundovic.guitarstab.service.CommentService;

public class CommentHibernateService implements CommentService{

	private final Session session;
	
	public CommentHibernateService(Session session) {
		this.session = session;
	}


	public List<Comment> retrieveAllComments() {
		// TODO Auto-generated method stub
		List<Comment> comments=session.createCriteria(CommentBean.class).list();
		return comments;
	}


	public void save(Comment comment) {
		// TODO Auto-generated method stub
		session.save(comment);
		
	}


	public boolean deleteComment(User user) {
		// TODO Auto-generated method stub
		List<Comment> comments=retrieveMine(user);
		if(comments.isEmpty())
			return false;
		for (int i = 0; i < comments.size(); i++) {
			comments.get(i).setComment(null);
			comments.get(i).setUser(null);
			session.delete(comments.get(i));
		}
		return true;
	}


	public List<Comment> retrieveMine(User user) {
		// TODO Auto-generated method stub
		List<Comment> comments=session.createCriteria(CommentBean.class).createCriteria("user").add(Restrictions.like("id",user.getId())).list();
		return comments;
	}
}
